// composables/useFieldEditor.js
import { ref, h, createApp } from 'vue';
import {
  ElMessageBox,
  ElMessage,
  ElDialog,
  ElDatePicker,
  ElButton,
} from 'element-plus';

/**
 * 通用字段编辑组合式函数
 * @param {Object} config 配置对象
 * @returns {Object} 编辑相关的方法和状态
 */
export function useFieldEditor(config = {}) {
  const loading = ref(false);

  /**
   * 快速编辑单个字段
   * @param {string|number} id 记录ID
   * @param {Object} options 编辑选项
   */
  const quickEdit = async (id, options = {}) => {
    const {
      title = '编辑',
      label = '请输入',
      field = 'value',
      currentValue = '',
      api,
      inputType = 'text',
      rules = {},
    } = { ...config, ...options };

    try {
      const { value } = await ElMessageBox.prompt(label, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: currentValue,
        inputType,
        inputValidator: (value) => {
          if (rules.required && !value) {
            return rules.message || '输入不能为空';
          }
          if (rules.min && Number(value) < rules.min) {
            return `值不能小于${rules.min}`;
          }
          if (rules.max && Number(value) > rules.max) {
            return `值不能大于${rules.max}`;
          }
          return true;
        },
      });

      if (api) {
        loading.value = true;
        await api({ id, [field]: value });
        ElMessage.success('修改成功');
        return { success: true, value };
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('修改失败');
        console.error('编辑失败:', error);
      }
      return { success: false, error };
    } finally {
      loading.value = false;
    }
  };

  /**
   * 创建自定义日期选择对话框
   * @param {Object} options 配置选项
   * @returns {Promise} 返回选择的日期值
   */
  const createDatePickerDialog = (options = {}) => {
    return new Promise((resolve, reject) => {
      const {
        title = '选择日期',
        type = 'date',
        format = 'YYYY-MM-DD',
        valueFormat = 'YYYY-MM-DD',
        placeholder = '请选择日期',
        startPlaceholder = '开始日期',
        endPlaceholder = '结束日期',
        currentValue = null,
        disabledDate = null,
        shortcuts = [],
        clearable = true,
        size = 'default',
        rules = {},
      } = options;

      let selectedValue = currentValue;
      let dialogVisible = true;

      // 创建对话框组件
      const DatePickerDialog = {
        setup() {
          const handleConfirm = () => {
            // 验证规则
            if (rules.required && !selectedValue) {
              ElMessage.error(rules.message || '请选择日期');
              return;
            }

            if (rules.minDate && selectedValue) {
              const selected = new Date(selectedValue);
              const minDate = new Date(rules.minDate);
              if (selected < minDate) {
                ElMessage.error(`日期不能早于 ${rules.minDate}`);
                return;
              }
            }

            if (rules.maxDate && selectedValue) {
              const selected = new Date(selectedValue);
              const maxDate = new Date(rules.maxDate);
              if (selected > maxDate) {
                ElMessage.error(`日期不能晚于 ${rules.maxDate}`);
                return;
              }
            }

            dialogVisible = false;
            resolve(selectedValue);
          };

          const handleCancel = () => {
            dialogVisible = false;
            reject('cancel');
          };

          const handleDateChange = (value) => {
            selectedValue = value;
          };

          const handleClose = () => {
            handleCancel();
          };

          return () =>
            h(
              ElDialog,
              {
                modelValue: dialogVisible,
                title,
                width: '420px',
                'destroy-on-close': true,
                'before-close': handleClose,
                'append-to-body': true,
              },
              {
                default: () => [
                  h('div', { style: 'padding: 20px 0;' }, [
                    h(ElDatePicker, {
                      modelValue: selectedValue,
                      type,
                      format,
                      'value-format': valueFormat,
                      placeholder: type.includes('range')
                        ? undefined
                        : placeholder,
                      'start-placeholder': type.includes('range')
                        ? startPlaceholder
                        : undefined,
                      'end-placeholder': type.includes('range')
                        ? endPlaceholder
                        : undefined,
                      'disabled-date': disabledDate,
                      shortcuts,
                      clearable,
                      size,
                      style: 'width: 100%',
                      'onUpdate:modelValue': handleDateChange,
                    }),
                  ]),
                ],
                footer: () =>
                  h('div', { class: 'dialog-footer' }, [
                    h(
                      ElButton,
                      {
                        onClick: handleCancel,
                        size,
                      },
                      '取消',
                    ),
                    h(
                      ElButton,
                      {
                        type: 'primary',
                        onClick: handleConfirm,
                        size,
                      },
                      '确定',
                    ),
                  ]),
              },
            );
        },
      };

      // 创建临时挂载点
      const mountPoint = document.createElement('div');
      document.body.appendChild(mountPoint);

      const app = createApp(DatePickerDialog);
      app.mount(mountPoint);

      // 清理函数
      const cleanup = () => {
        try {
          app.unmount();
          if (document.body.contains(mountPoint)) {
            document.body.removeChild(mountPoint);
          }
        } catch (e) {
          console.warn('清理对话框时出错:', e);
        }
      };

      // 在resolve或reject后清理
      const originalResolve = resolve;
      const originalReject = reject;
      resolve = (value) => {
        cleanup();
        originalResolve(value);
      };
      reject = (reason) => {
        cleanup();
        originalReject(reason);
      };
    });
  };

  /**
   * 数字字段快速编辑
   */
  const editNumber = (id, options = {}) => {
    return quickEdit(id, {
      ...options,
      inputType: 'number',
      rules: {
        required: true,
        min: 0,
        message: '请输入有效数字',
        ...options.rules,
      },
    });
  };

  /**
   * 文本字段快速编辑
   */
  const editText = (id, options = {}) => {
    return quickEdit(id, {
      ...options,
      inputType: 'text',
      rules: {
        required: true,
        message: '请输入内容',
        ...options.rules,
      },
    });
  };

  /**
   * 日期字段快速编辑 - 使用 el-date-picker
   * @param {string|number} id 记录ID
   * @param {Object} options 编辑选项
   */
  const editDate = async (id, options = {}) => {
    const {
      title = '编辑日期',
      field = 'date',
      currentValue = null,
      api,
      type = 'date',
      format = 'YYYY-MM-DD',
      valueFormat = 'YYYY-MM-DD',
      placeholder = '请选择日期',
      disabledDate = null,
      shortcuts = [],
      clearable = true,
      size = 'default',
      rules = {},
    } = { ...config, ...options };

    try {
      const selectedValue = await createDatePickerDialog({
        title,
        type,
        format,
        valueFormat,
        placeholder,
        currentValue,
        disabledDate,
        shortcuts,
        clearable,
        size,
        rules: {
          required: true,
          message: '请选择日期',
          ...rules,
        },
      });

      if (api && selectedValue !== undefined) {
        loading.value = true;
        await api({ id, [field]: selectedValue });
        ElMessage.success('修改成功');
        return { success: true, value: selectedValue };
      }

      return { success: true, value: selectedValue };
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('修改失败');
        console.error('编辑失败:', error);
      }
      return { success: false, error };
    } finally {
      loading.value = false;
    }
  };

  /**
   * 日期时间字段快速编辑
   */
  const editDateTime = (id, options = {}) => {
    return editDate(id, {
      title: '编辑日期时间',
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      placeholder: '请选择日期时间',
      ...options,
    });
  };

  /**
   * 日期范围字段快速编辑
   */
  const editDateRange = (id, options = {}) => {
    return editDate(id, {
      title: '编辑日期范围',
      type: 'daterange',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      startPlaceholder: '开始日期',
      endPlaceholder: '结束日期',
      ...options,
    });
  };

  /**
   * 日期时间范围字段快速编辑
   */
  const editDateTimeRange = (id, options = {}) => {
    return editDate(id, {
      title: '编辑日期时间范围',
      type: 'datetimerange',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间',
      ...options,
    });
  };

  /**
   * 月份字段快速编辑
   */
  const editMonth = (id, options = {}) => {
    return editDate(id, {
      title: '编辑月份',
      type: 'month',
      format: 'YYYY-MM',
      valueFormat: 'YYYY-MM',
      placeholder: '请选择月份',
      ...options,
    });
  };

  /**
   * 年份字段快速编辑
   */
  const editYear = (id, options = {}) => {
    return editDate(id, {
      title: '编辑年份',
      type: 'year',
      format: 'YYYY',
      valueFormat: 'YYYY',
      placeholder: '请选择年份',
      ...options,
    });
  };

  /**
   * 周字段快速编辑
   */
  const editWeek = (id, options = {}) => {
    return editDate(id, {
      title: '编辑周',
      type: 'week',
      format: 'YYYY 第 ww 周',
      valueFormat: 'YYYY-[W]WW',
      placeholder: '请选择周',
      ...options,
    });
  };

  return {
    loading,
    quickEdit,
    editNumber,
    editText,
    editDate,
    editDateTime,
    editDateRange,
    editDateTimeRange,
    editMonth,
    editYear,
    editWeek,
    createDatePickerDialog,
  };
}

// 使用示例：
/*
// 在组件中使用
import { useFieldEditor } from '@/composables/useFieldEditor'

export default {
  setup() {
    const { 
      editNumber, 
      editText, 
      editDate, 
      editDateTime, 
      editDateRange,
      editMonth,
      editYear 
    } = useFieldEditor()
    
    // 编辑工资
    const editSalary = (id, currentSalary) => {
      editNumber(id, {
        title: '修改工资',
        label: '请输入新工资',
        field: 'salary',
        currentValue: currentSalary,
        api: async (data) => {
          await api.updateSalary(data)
        }
      })
    }
    
    // 编辑姓名
    const editName = (id, currentName) => {
      editText(id, {
        title: '修改姓名',
        label: '请输入姓名',
        field: 'name',
        currentValue: currentName,
        api: async (data) => {
          await api.updateName(data)
        }
      })
    }

    // 编辑生日 - 使用 el-date-picker
    const editBirthday = (id, currentBirthday) => {
      editDate(id, {
        title: '修改生日',
        field: 'birthday',
        currentValue: currentBirthday,
        type: 'date',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        placeholder: '请选择生日',
        disabledDate: (time) => {
          // 禁用未来日期
          return time.getTime() > Date.now()
        },
        shortcuts: [
          {
            text: '今天',
            value: new Date()
          },
          {
            text: '一周前',
            value: (() => {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              return date
            })()
          }
        ],
        rules: {
          required: true,
          message: '请选择生日'
        },
        api: async (data) => {
          await api.updateBirthday(data)
        }
      })
    }

    // 编辑入职时间 - 使用日期时间选择器
    const editHireDateTime = (id, currentHireDateTime) => {
      editDateTime(id, {
        title: '修改入职时间',
        field: 'hire_datetime',
        currentValue: currentHireDateTime,
        placeholder: '请选择入职日期和时间',
        api: async (data) => {
          await api.updateHireDateTime(data)
        }
      })
    }

    // 编辑项目周期 - 使用日期范围选择器
    const editProjectPeriod = (id, currentPeriod) => {
      editDateRange(id, {
        title: '修改项目周期',
        field: 'project_period',
        currentValue: currentPeriod, // 应该是一个数组 [startDate, endDate]
        startPlaceholder: '项目开始日期',
        endPlaceholder: '项目结束日期',
        api: async (data) => {
          await api.updateProjectPeriod(data)
        }
      })
    }

    // 编辑入职月份
    const editHireMonth = (id, currentMonth) => {
      editMonth(id, {
        title: '修改入职月份',
        field: 'hire_month',
        currentValue: currentMonth,
        api: async (data) => {
          await api.updateHireMonth(data)
        }
      })
    }

    // 编辑毕业年份
    const editGraduationYear = (id, currentYear) => {
      editYear(id, {
        title: '修改毕业年份',
        field: 'graduation_year',
        currentValue: currentYear,
        api: async (data) => {
          await api.updateGraduationYear(data)
        }
      })
    }
    
    return {
      editSalary,
      editName,
      editBirthday,
      editHireDateTime,
      editProjectPeriod,
      editHireMonth,
      editGraduationYear
    }
  }
}
*/
